package api

import (
	"fmt"
	"mytest/initialize/database"
	"mytest/models"
	"mytest/models/request"
	"mytest/service/system"
	"net/http"

	"github.com/gin-gonic/gin"
)

//接受参数，调用service接口
func CreateAuth(c *gin.Context) {
	var form models.SysAuthority
	if e := c.Bind(&form); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	if form.ParentId == "" || form.AuthorityId == "" || form.AuthorityName == "" {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("参数不完整"),
		})
		return
	}
	db := database.GetDB()
	e, auth := system.CreateAuthority(db, form)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("角色插入失败: %v", e.Error()),
		})

		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Data: auth,
	})
}

//删除角色
func DeleteAuthority(c *gin.Context) {
	var form request.GetById
	if e := c.Bind(&form); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	if form.Auth == "" {
		c.String(http.StatusOK, "输入角色id")
		return
	}
	if claim, exists := c.Get("claims"); !exists {
		c.String(http.StatusOK, "从Gin的Context中获取从jwt解析出来的用户authorityId失败, 请检查路由是否使用jwt中间件")
		return
	} else {
		authId := claim.(*request.CustomClaims).AuthorityId
		if authId == form.Auth {
			c.JSON(http.StatusOK, UniversalResp{
				Code: 1,
				Msg:  "自杀失败",
			})
			return
		}
	}
	db := database.GetDB()
	e := system.DeleteAuthority(db, form.Auth)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("角色删除失败: %v", e.Error()),
		})

		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Msg: "success",
	})
}
func UpdateAuthority(c *gin.Context) {
	var form models.SysAuthority
	if e := c.Bind(&form); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	db := database.GetDB()
	e := system.UpdateAuth(db, &form)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("角色更新失败: %v", e.Error()),
		})

		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Msg: "update success",
	})
}

//查看角色信息
func GetAllAuthority(c *gin.Context) {

	db := database.GetDB()
	e, auths := system.GetAllAuthority(db)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("角色查看失败: %v", e.Error()),
		})

		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Data: auths,
	})
}
func GetAllAuthorityFlat(c *gin.Context) {
	e, outs := system.GetAllAuthorityFlat(database.GetDB())
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("角色查看失败: %v", e.Error()),
		})

		return
	}
	c.JSON(http.StatusOK, UniversalResp{
		Data: outs,
	})
}
